var express = require('express');
var md5 = require("md5")
const query = require('../config/db');
var router = express.Router();

// 首页
//轮播图接口
router.get("/banner", async (req, res, next) => {
    let sql = `SELECT * FROM e_banners WHERE isshow=1`;
    let result = await query(sql);
    res.send({
        success: true,
        msg: "查询成功",
        status: 200,
        data: result
    })
})

// 课程列表
router.get("/course",async(req,res,next)=>{
    let sql = `select * from e_course where type='${req.query.type}'`
    let result = await query(sql)
    res.send({
        success:true,
        msg:"查询成功",
        status:200,
        data:result
    })
})

// 注册接口
router.post("/register",async(req,res,next)=>{
    let {username,password,createdate} = req.body
    let sql2 = `select * from e_member where username = '${username}'`
    let result2 = await query(sql2)
    if(result2.length>0){
        next("该用户已经注册过了")
        return
    }

    password = md5(md5(password).substr(5,6))
    // 注册
    let mid = new Date().getTime()+(Math.random()+'').substr(2,6)
    let sql1 = `insert into e_member (mid,username,password,sex,createdate) values ('${mid}','${username}','${password}','1','${createdate}')`
    let result1 = await query(sql1)
    if(result1.affectedRows>0){
        res.send({
            success:true,
            msg:"注册成功",
            status:200
        })
    }else{
        next("注册失败")
    }
})

// 登录
router.post("/login",async(req,res,next)=>{
    let {username,password} = req.body
    let sql2 = `select * from e_member where username = '${username}'`
    let result2 = await query(sql2)
    password = md5(md5(password).substr(5,6))
    if(result2.length >0){
        if(password == result2[0].password){
            res.send({
                success:true,
                msg:"登陆成功",
                status:200,
                // data:result2[0]
            })
        }else{
            next("用户名密码错误")
            return
        }
    }else{
        next("用户不存在")
        return
    }
})
module.exports = router;
